package com.thoughtworks.impersonator.http.replay;

import java.io.File;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.thoughtworks.impersonator.http.message.RequestIdentifier;
import com.thoughtworks.impersonator.http.message.storage.HttpExchangeSerialiser;
import com.thoughtworks.impersonator.http.message.storage.HttpExchangeStorage;
import com.thoughtworks.impersonator.http.message.transform.DefaultRequestTransformer;
import com.thoughtworks.impersonator.http.message.transform.DefaultResponseTransformer;
import com.thoughtworks.impersonator.http.message.transform.ResponseTransformer;

public class Impersonator {

    private Channel channel;
    private NioServerSocketChannelFactory channelFactory;

    public Impersonator(int localport, File storageDir, RequestIdentifier requestIdentifier) {
        this(localport, storageDir, requestIdentifier, new DefaultResponseTransformer());
    }

    public Impersonator(int localport, File storageDir, RequestIdentifier requestIdentifier,
            ResponseTransformer responseTransformer) {
        HttpExchangeSerialiser serialiser = new HttpExchangeSerialiser(requestIdentifier, new DefaultRequestTransformer(), responseTransformer);
        HttpExchangeStorage storage = new HttpExchangeStorage(storageDir, serialiser);
        ExecutorService threadPool = Executors.newCachedThreadPool();
        channelFactory = new NioServerSocketChannelFactory(threadPool, threadPool);
        ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
        bootstrap.setPipelineFactory(new ImpersonatorPipelineFactory(storage));
        channel = bootstrap.bind(new InetSocketAddress(localport));
    }

    public void stop() {
        channel.close().awaitUninterruptibly();
    }

}
